/**     
* @Title: AuthcTokenAuthenticationFilter.java   
* @Package com.yitong.spring.filter   
* @Description: TODO
* @author weiwei 
* @date 2017年7月21日 下午6:21:52   
* @version V1.0     
*/
package com.yitong.spring.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import com.alibaba.fastjson.JSON;
import com.yitong.utils.ConstantUtils;
import com.yitong.utils.RetCode;
import com.yitong.utils.RspUtils;
import com.yitong.utils.SessionUtils;

/**
 * @ClassName: AuthcTokenAuthenticationFilter
 * @Description: TODO
 * @author weiwei
 * @date 2017年7月21日 下午6:21:52
 * 
 */
public class AuthcTokenAuthenticationFilter extends AuthenticationFilter {

	private static final String AUTHC_TOKEN_PARAM_NAME = "authcToken";

	@Override
	protected boolean onAccessDenied(ServletRequest req, ServletResponse rsp) throws Exception {
		if (isLoginRequest(req, rsp)) {
			return true;
		}
		// 从url获取
		String authcToken = WebUtils.getCleanParam(req, AUTHC_TOKEN_PARAM_NAME);
		// 从headder获取
		if (StringUtils.isBlank(authcToken)) {
			authcToken = WebUtils.toHttp(req).getHeader(AUTHC_TOKEN_PARAM_NAME);
		}
		if (StringUtils.isNotBlank(authcToken)) {
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session != null) {
				String token = SessionUtils.getAuthcToken();
				if (authcToken.equals(token)) {
					return true;
				}
			}
		}
		issueDenied(WebUtils.toHttp(req), WebUtils.toHttp(rsp));
		return false;
	}

	private void issueDenied(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
		Map<String, Object> ret = RspUtils.makeRsp(RetCode.FORBIDDEN, "拒绝访问");
		rsp.setContentType(ConstantUtils.CONTENT_TYPE_APPLICATION_JSON);
		String json = JSON.toJSONString(ret, false);
		rsp.getWriter().write(json);
		rsp.flushBuffer();
	}
}
